package com.example.demo.controller;

import com.example.demo.component.OnlineUserManager;
import com.example.demo.mapper.MessageMapper;
import com.example.demo.mapper.MessageSessionMapper;
import com.example.demo.model.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.List;

@RestController
public class WebSocketController extends TestWebSocketController{

    @Autowired
    private static Logger log = LoggerFactory.getLogger(WebSocketController.class);

    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //在服务端和客户端成功连接后自动调用
        log.info("客户端服务端连接成功");
        User user = (User)session.getAttributes().get("user"); //getAttributes 是将HttpSession拷贝到WebSocketSession中的所有Session取出来放到一个hashmap中
        //System.out.println("用户的userId:" + user.getUserId());
        onlineUserManager.online(user.getUserId(),session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //服务端收到消息后自动调用 message变量就是服务端收到的消息
        log.info("服务端收到客户端发来的消息" + message.toString());

        //消息的接收,保存,转发
        //1.获取到当前用户的信息
        User user = (User) session.getAttributes().get("user");
        if(user == null)
        {
            log.info("用户未登录");
        }
        //把json格式的请求转化为一个java实体类对象
        MessageRequest req = objectMapper.readValue(message.getPayload(),MessageRequest.class);
        if(req.getType().equals("message")) //如果请求的type是message就保存并转发消息
        {
             transferMessage(user,req);//转发
        }
        else
        {
            log.warn("");
        }

    }

    //fromUser是谁发来的用户
    private void transferMessage(User fromUser, MessageRequest req) throws IOException {
        //1.先构造一个响应 MessageResponse
        MessageResponse resp = new MessageResponse();
        resp.setType("message");
        resp.setFromId(fromUser.getUserId());
        resp.setFromName(fromUser.getUsername());
        resp.setSessionId(req.getSessionId());
        resp.setContent(req.getContent());
        //把这个java对象转为json格式
        String respJson = objectMapper.writeValueAsString(resp);

        //2.根据请求中的 sessionId 获取到这个 MessageSession中都有哪些用户,通过查询数据库就可以知道
        List<Friend> friends = messageSessionMapper.getFriendsBySessionId(req.getSessionId(),fromUser.getUserId());
        //但是由于查询数据库会把发消息的用户排除掉,但是最终转发的时候也需要将消息发给发送消息的人一份
        Friend myself = new Friend(fromUser.getUserId(),fromUser.getUsername());
        friends.add(myself);

        //3.循环遍历上述列表,给列表中的每个用户发一份响应消息
        //注意:还要给自己发一份,方便在自己的客户端上显示自己发的消息
        for(Friend friend : friends)
        {
            WebSocketSession webSocketSession = onlineUserManager.getSession(friend.getFriendId());
            if(webSocketSession == null)
            {
                //如果用户不在线,先不发
                continue;
            }
            webSocketSession.sendMessage(new TextMessage(respJson));
        }

        //4.转发的消息还要加入到数据库中
        Message message = new Message();
        message.setContent(req.getContent());
        message.setFromId(fromUser.getUserId());
        message.setSessionId(req.getSessionId());

        messageMapper.add(message);
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //客户端服务端连接出现异常后自动调用 exception就是收到的异常
        log.warn("服务端和客户端连接出现异常");

        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //连接正常关闭后,自动调用的
        log.info("服务端客户端连接正常关闭");

        User user = (User) session.getAttributes().get("user");
        if(user == null) {
            return;
        }
        onlineUserManager.offline(user.getUserId(),session);
    }
}

